<template>
  <div class="cart">
    <div class="header">
      <van-nav-bar title="确认下单" fixed left-text="返回" right-text left-arrow @click-left="onClickLeft"/>
    </div>
      <!--没有地址跳转显示-->
      <div class="cart_address">
        <div class="cart_address1" @click="linkAddress()" v-if="!addressData">
        <div class="cart_address_con1">
          <p class="cart_address_con_p">请选择地址</p>
        </div>
        <div>
          <i class="icon iconfont icon-xiayige"></i>
        </div>
        </div>
      <!--有地址时显示-->
        <div class="cart_address1" @click="linkAddress()" v-if="addressData">
        <i class="icon iconfont icon-icon-test"></i>
        <div class="cart_address_con">
          <p>{{addressData.name}}<span>{{addressData.phone}}</span></p>
          <p>{{addressData.province}}{{addressData.city}}{{addressData.county}}{{addressData.detailed}}</p>
        </div>
        <div>
          <i class="icon iconfont icon-xiayige"></i>
        </div>
      </div>
    </div>
  <div class="cart_shop">
    <div class="cart_shop_name">
         {{Titlename}}
    </div>
              <div class="cart_shop_car">
                  <div class="cart_shop_car_img">
                      <img :src="image_url" />
                  </div>
                  <div class="cart_shop_car_detail">
                      <div class="cart_shop_car_detail_title">{{shop_name}}</div>
                      <div class="cart_shop_car_detail_data">
                          <div class="cart_shop_car_detail_data_div">规格/型号 {{product_detail_group_name}} </div>
                          <div class="cart_shop_car_detail_data_div1"><span class="gy_price_mark">￥</span><span class="gy_price_num">{{price}}</span></div>
                      </div>
                  </div>
              </div>

     <div class="cart_number_element1">
            <div class="number_element1_num">购买数量</div>
      <div class="cart_number_element1_right2">
            <div @click="delete_number()" class="add_del_botton1">-</div>
            <input type="text"  name="input1" :value="buymin" readonly="true">
             <div @click="add_number()" class="add_del_botton1">+</div>
      </div>
    </div>
    <div class="cart_number_element1">
       <div class="number_element1_num">运费</div>
      <div class="cart_number_element1_right1">￥{{Freight||'0'}}</div>
    </div>
  </div>
   <div class="cart_textarea">
    <p>备注</p>
    <textarea placeholder="请输入备注信息" rows="4" cols="48" v-model.trim="Remarks">{{addressData}}</textarea>
    </div>    
    <div class="cart_buttom-show">
      <div class="cart_bottom-item-button" @click="">
				<p>总价：<span class="gy_price_mark">￥</span><span class="gy_price_num">{{total}}</span></p>
			</div>
              <div class="cart_bottom-item-button1">
                 <button @click="Submit()">提交订单</button>
              </div>
          </div>
      </div>
</template>
<script>
  // import {getCookie, setCookie,authorLogin} from "../../utils/util";
  export default {
    data() {
      return {
        showname:false,//判断是否有地址
        shop_name:this.$route.query.shop_name,
        Titlename:this.$route.query.Titlename,
        buymin:this.$route.query.buymin,
        product_detail_group_name:this.$route.query.product_name,
        type:this.$route.query.type,
        price:this.$route.query.price,
        image_url:this.$route.query.img,
        id:this.$route.query.repository_id,
        restrict_count:this.$route.query.restrict_count,
        is_show: true,
        dianji: 0,
        addressData:JSON.parse(localStorage.getItem('Address')),
        commonList: [],
        Freight:'',
        show: false,
        show1: false,
        page:1,
        Remarks:'',
        moneyType:'',
        // addressDataOne:[],
      }
    },
    components: {

    },
    mounted: function() {
      //生命周期
      // this.getCommodityCart()
      this.getFreight()
      setTitle('确认下单')
    },
    computed: {
      //计算总价
      total : function(){
        var total = 0;
        total= Number(this.price * this.buymin)+Number(this.Freight||0)
        total=total.toFixed(2)
        return total;
      }
    },
    methods: {
      //返回
      onClickLeft() {
        this.$router.go(-1);
      },
      //跳转用户地址
      linkAddress(){
        this.$router.push({path: '/Address'})
      },
      async getClassification() {
        let params = {

        };
        const res = await this.$axios.get(this.$api.navData, params);
        if (res.data.success) {
          this.navList = res.data.data;
        } else {
          this.$toast(res.data.msg);
        }
      },
      //调用用户地址
      // async getUserAddress(){
      //   var list=[]
      //   var list=JSON.parse(localStorage.getItem('userInfo'))
      //   this.list=list
      //   var userID =list.userId;
      //   let params = {
      //     user_id:userID,
      //   };
      //   const res = await this.$axios.post(this.$api.UserAddressData, params);
      //   if (res.success) {
      //     this.addressData = res.data;
      //     this.addressDataOne = res;
      //     this.getFreight(this.addressData)
      //     console.log('8255',this.addressData);
      //     if(this.addressData){
      //       this.showname=true
      //     }else {
      //       this.showname=false
      //     }
      //   } else {
      //     this.$toast(res.msg);
      //   }
      // },
      //运费
      async getFreight(){
		  if(!this.addressData){
			this.Freight = 0;
		  }else {
			let params = {
			   productId:this.$route.query.id,
			   enterpriseId:this.$route.query.shop_id,
			   buyNum:this.buymin,
			   address:this.addressData.province,
			};
			const res = await this.$axios.post(this.$api.getpriceData, params);
			if (res.success) {
			  this.Freight = res.data;
			  console.log("运费",this.Freight)
			}else {
			   this.$toast(res.msg);
			 }
		  }
     },
      //点击数量增加
      add_number() {
        if(this.restrict_count == this.buymin ){
          return
        }else {
          this.buymin = Number(this.buymin) + 1
        }
      },
      //点击数量减掉
      delete_number() {
        if(this.buymin == 1) {
          return ;
        } else {
          this.buymin = Number(this.buymin) - 1
        }
      },
       Submit(){
        if(!this.addressData){
          this.$toast("请添加地址");
        }else {
          this.SubmitOrder(this.addressData)
        }
      },
      async SubmitOrder() {
        let this_ = this;
        var userList = [];
        var userList = JSON.parse(localStorage.getItem('userInfo'));
        this.userList = userList;
        var userID = userList.userId;
        var openID = userList.openId;
		console.log(this.addressData)
        let params = {
          buyerMessage: this_.Remarks,//备注
          shippingAddressId:this_.addressData.id,//地址id
          spellGroupType: 1,//价格
          quantity: this_.buymin,//数量
          openId: openID,
          repositoryId: this_.id,
          gwj:0
        };
        var apiUrl=this.$api.payData;
        if(this.type!="1"){
            apiUrl=this.$api.payNewData;
            params.paymentChannel=1;
            params.spellGroupType=16;
        }

		console.log(params)

        const res = await this.$axios.post(apiUrl, params);


        if (res.success) {
          var json = res.data.order_num
          console.log('zf', json)
          console.log(res)
          this.$router.push({path: '/wxPay',query:{order_id:json}})

          // this.$ajax({
          //   method:"post",
          //   url: '/api/common/v1/order/purchase-immediately',
          //   data:{
          //     buyerMessage:this_.Remarks,//备注
          //     shippingAddressId:addressData.id,//地址id
          //     spellGroupType: 1,//价格
          //     quantity:this_.buymin,//数量
          //     openId:openID,
          //     repositoryId:this_.id,
          //   },
          //   transformRequest: [function (data) {
          //     let ret = ''
          //     for (let it in data) {
          //       ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
          //     }
          //     return ret
          //   }],
          //   headers: {
          //     'Content-Type':'application/x-www-form-urlencoded',
          //     'Authorization': 'Bearer '+getCookie("token")
          //   }
          // }).then(res=>{
          //   var json = res.data.data
          //   if(res.data.success){
          //     function onBridgeReady(){
          //       WeixinJSBridge.invoke(
          //         'getBrandWCPayRequest', {
          //           "appId":json.appId,     //公众号名称，由商户传入
          //           "timeStamp":json.timeStamp,  //时间戳，自1970年以来的秒数
          //           "nonceStr":json.nonceStr, //随机串
          //           "package":json.package,
          //           "signType":"MD5",         //微信签名方式：
          //           "paySign":json.paySign //微信签名
          //         },
          //         function(res){
          //           if(res.err_msg == "get_brand_wcpay_request:ok" ){
          //             //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
          //             window.location.href='http://pay.zjc158.com/stcwx/#/User'
          //             // this.$router.push({path: '/AllOrders'})
          //           }
          //         });
          //     }
          //     if (typeof WeixinJSBridge == "undefined"){
          //       if( document.addEventListener ){
          //         document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
          //       }else if (document.attachEvent){
          //         document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
          //         document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
          //       }
          //     }else {
          //       onBridgeReady();
          //     }

        } else {
          this.$toast(res.msg);
        }
      }
    },
    created: function() {
      this.$emit('public_footer',false);
    }
  }
</script>
 
<style scoped>
  @import '../../assets/css/index.css';
  .mint-radio-input:checked + .mint-radio-core {
    background-color: #01bf47!important;
    border-color: #01bf47!important;
  }
</style>

